<?php

class MailConversationController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('sendMailTouser'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('inbox', 'sendMailTouser', 'GetMessage', 'getconverteduserClass', 'getconverteduserCourses'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionsendMailTouser() {
        $this->layout = FALSE;
        if (isset($_POST['makeQueryId']) && $_POST['makeQueryId'] <> "") {
            $modelMake = MakeQuery::model()->findByPk($_POST['makeQueryId']);
            MakeQuery::model()->updateByPk($modelMake->id, array('mail_sent' => SkillConfig::STATUS_ACTIVE));
        }
        if (isset($_POST['msgval'])) {
            if ($_POST['type'] != 'course') {
                $courseClassId = 'classes_id';
                $classes = Classes::model()->findByPk($_POST['classId']);
                $classCourseName = $classes->class_titile;
            } else {
                $courseClassId = 'courses_id';
                $classes = Courses::model()->findByPk($_POST['classId']);
                $classCourseName = $classes->course_titile;
            }

            $arrayVal = explode(',', $_POST['selectedUser']);
            foreach ($arrayVal as $userVal) {
                $model = new MailConversation;
                $model->setAttribute($courseClassId, $_POST['classId']);
                $model->setAttribute('to_user_id', $userVal);
                $model->setAttribute('mail_subject', $_POST['subject']);
                $model->setAttribute('mail_message', $_POST['msgval']);
                $model->setAttribute('from_users_id', getLoginUserId());
                $model->setAttribute('make_query_id', $_POST['makeQueryId']);
                $model->setAttribute('created_time', SkillConfig::CreateDateTime());
                $userdetails = Users::getFrontEndUser($userVal);
                $trainername = Users::getFrontEndUser(getLoginUserId());
                $model->save();
                $mailmodel = EmailTemplate::model()->findByPk(Message::CLASS_COURSE_QUERY_NOTIFICATION);
                $userText = $mailmodel->body;
                $mailbody = array('value' => $userText, 'type' => 'raw');
                $userName = $userdetails->first_name . ' ' . $userdetails->last_name;
                $trainernames = $trainername->first_name . ' ' . $trainername->last_name;
                $mailto = $userdetails->user->username;               
                $classCourseViewdetailsLink = '<a class="linkclass" href="http://' . SITE_URL . '/users/myskillhippo"> View Inbox</a>';
                $arrayFind = array('[username]', '[from_user_name]', '[classcoursename]', '[classCourseViewdetailsLink]');
                $arrayReplace = array($userName, $trainernames, $classCourseName, $classCourseViewdetailsLink);
                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                $subject = $mailmodel->subject;
                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                
                try {
                    SkillSendMail::SendMail($mailto, $subject, $body);
                    $result = 'success';
                } catch (Exception $e) {
                    $result = $e;
                    exit;
                }
            }
            if ($result == 'success') {
                echo 'success';
            }
            Yii::app()->end();
        }
    }

    public function actionInbox() {
        $this->layout = FALSE;
        $criteria = new CDbCriteria;
        $criteria->group = 'from_users_id';
        $criteria->condition = 'to_user_id = ' . getLoginUserId();
        $allUsers = MailConversation::model()->findAll($criteria);
        $allconvertedQuery = MakeQuery::model()->findAll('created_by=' . getLoginUserId());

        $this->render('inbox', array('allusers' => $allUsers, 'allconvertedQuery' => $allconvertedQuery));
    }

    public function actionGetMessage() {
        $this->layout = FALSE;
        $userdata = "";
        $criteria = new CDbCriteria;
        if ($_POST['type'] != SkillConfig::class_name) {
            $criteria->condition = '(to_user_id = ' . $_POST['touid'] . ' AND from_users_id =' . $_POST['fromuid'] . ') OR (to_user_id = ' . $_POST['fromuid'] . ' AND from_users_id = ' . $_POST['touid'] . ') AND courses_id=' . $_POST['classid'];
        } else {
            $criteria->condition = '(to_user_id = ' . $_POST['touid'] . ' AND from_users_id =' . $_POST['fromuid'] . ') OR (to_user_id = ' . $_POST['fromuid'] . ' AND from_users_id = ' . $_POST['touid'] . ') AND classes_id=' . $_POST['classid'];
        }$dataByUser = MailConversation::model()->findAll($criteria);
        $this->renderPartial('//mailConversation/mailconversion', array('dataByUser' => $dataByUser));
    }

    public function actiongetconverteduserClass() {
        $this->layout = FALSE;
        if (isset($_POST['classid'])) {
            $convertedUser = MakeQuery::getClassConvertedUser($_POST['classid']);
            $this->renderPartial('//mailConversation/convertedClassUser', array('dataByUsers' => $convertedUser));
        } else {
            throw new CHttpException(403, 'You are not authorized to perform this action.');
        }
    }

    public function actiongetconverteduserCourses() {
        $this->layout = FALSE;
        if (isset($_POST['courseId'])) {
            $convertedUser = MakeQuery::getCourseConvertedUser($_POST['courseId']);
            $this->renderPartial('//mailConversation/convertedCourseUser', array('dataByUsers' => $convertedUser));
        } else {
            throw new CHttpException(403, 'You are not authorized to perform this action.');
        }
    }

}